<template>
  <div class="forwarding-container">
    <el-card class="forwarding-card">
      <template #header>
        <div class="card-header">
          <h2>消息转发设置</h2>
          <el-button type="primary" @click="fetchGroups" :loading="isLoading">刷新群组列表</el-button>
        </div>
      </template>
      
      <el-alert
        v-if="!wechatStore.isRunning"
        title="微信服务未运行"
        type="warning"
        description="请先在首页启动微信服务，才能获取群组和用户信息。"
        show-icon
        :closable="false"
      />
      
      <el-tabs v-model="activeTab">
        <el-tab-pane label="选择群组" name="groups">
          <div class="tab-content">
            <el-input
              v-model="groupSearchKeyword"
              placeholder="搜索群组名称"
              clearable
              prefix-icon="el-icon-search"
              class="search-input"
            />
            
            <el-table
              v-loading="isLoading"
              :data="filteredGroups"
              style="width: 100%"
              @selection-change="handleGroupSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="name" label="群组名称" />
              <el-table-column prop="member_count" label="成员数量" width="100" />
              <el-table-column label="操作" width="150">
                <template #default="scope">
                  <el-button 
                    type="primary" 
                    size="small" 
                    @click="viewGroupMembers(scope.row)"
                  >
                    查看成员
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="选择用户" name="users">
          <div class="tab-content">
            <el-alert
              v-if="!selectedGroup"
              title="请先选择一个群组"
              type="info"
              description="在选择群组标签页中选择一个群组，然后在这里查看和选择群成员。"
              show-icon
              :closable="false"
              style="margin-bottom: 15px;"
            />
            
            <template v-if="selectedGroup">
              <div class="selected-group-info">
                <h3>当前选择的群组: {{ selectedGroup.name }}</h3>
              </div>
              
              <el-input
                v-model="userSearchKeyword"
                placeholder="搜索用户名称"
                clearable
                prefix-icon="el-icon-search"
                class="search-input"
              />
              
              <el-table
                v-loading="isLoadingMembers"
                :data="filteredUsers"
                style="width: 100%"
                @selection-change="handleUserSelectionChange"
              >
                <el-table-column type="selection" width="55" />
                <el-table-column prop="name" label="用户名称" />
                <el-table-column prop="wxid" label="微信ID" width="200" />
              </el-table>
            </template>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="转发规则" name="rules">
          <div class="tab-content">
            <div class="rules-header">
              <h3>转发规则列表</h3>
              <el-button type="primary" @click="showAddRuleDialog">添加规则</el-button>
            </div>
            
            <el-table
              :data="wechatStore.forwardingRules"
              style="width: 100%"
            >
              <el-table-column prop="name" label="规则名称" />
              <el-table-column prop="sourceGroup.name" label="来源群组" />
              <el-table-column prop="sourceUser.name" label="来源用户" />
              <el-table-column prop="targetUser.name" label="转发目标" />
              <el-table-column prop="enabled" label="状态">
                <template #default="scope">
                  <el-tag :type="scope.row.enabled ? 'success' : 'info'">
                    {{ scope.row.enabled ? '启用' : '禁用' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200">
                <template #default="scope">
                  <el-button 
                    type="primary" 
                    size="small" 
                    @click="editRule(scope.row, scope.$index)"
                  >
                    编辑
                  </el-button>
                  <el-button 
                    type="danger" 
                    size="small" 
                    @click="deleteRule(scope.$index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    
    <!-- 添加/编辑规则对话框 -->
    <el-dialog
      v-model="ruleDialogVisible"
      :title="isEditingRule ? '编辑转发规则' : '添加转发规则'"
      width="500px"
    >
      <el-form :model="ruleForm" label-width="100px">
        <el-form-item label="规则名称">
          <el-input v-model="ruleForm.name" placeholder="请输入规则名称" />
        </el-form-item>
        
        <el-form-item label="来源群组">
          <el-select v-model="ruleForm.sourceGroup" placeholder="选择来源群组" style="width: 100%">
            <el-option
              v-for="group in selectedGroups"
              :key="group.wxid"
              :label="group.name"
              :value="group"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="来源用户">
          <el-select v-model="ruleForm.sourceUser" placeholder="选择来源用户" style="width: 100%">
            <el-option
              v-for="user in selectedUsers"
              :key="user.wxid"
              :label="user.name"
              :value="user"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="转发目标">
          <el-select v-model="ruleForm.targetUser" placeholder="选择转发目标" style="width: 100%">
            <el-option
              v-for="contact in contacts"
              :key="contact.wxid"
              :label="contact.name"
              :value="contact"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-switch v-model="ruleForm.enabled" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="ruleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveRule">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useWechatStore } from '../store';
import { ElMessage, ElMessageBox } from 'element-plus';

const wechatStore = useWechatStore();
const activeTab = ref('groups');
const isLoading = ref(false);
const isLoadingMembers = ref(false);
const groups = ref([]);
const users = ref([]);
const contacts = ref([]);
const selectedGroup = ref(null);
const groupSearchKeyword = ref('');
const userSearchKeyword = ref('');
const selectedGroups = ref([]);
const selectedUsers = ref([]);

// 规则表单
const ruleDialogVisible = ref(false);
const isEditingRule = ref(false);
const editingRuleIndex = ref(-1);
const ruleForm = ref({
  name: '',
  sourceGroup: null,
  sourceUser: null,
  targetUser: null,
  enabled: true
});

// 过滤后的群组列表
const filteredGroups = computed(() => {
  if (!groupSearchKeyword.value) return groups.value;
  return groups.value.filter(group => 
    group.name.toLowerCase().includes(groupSearchKeyword.value.toLowerCase())
  );
});

// 过滤后的用户列表
const filteredUsers = computed(() => {
  if (!userSearchKeyword.value) return users.value;
  return users.value.filter(user => 
    user.name.toLowerCase().includes(userSearchKeyword.value.toLowerCase())
  );
});

// 获取群组列表
async function fetchGroups() {
  if (!wechatStore.isRunning) {
    ElMessage.warning('微信服务未运行，无法获取群组列表');
    return;
  }
  
  isLoading.value = true;
  try {
    const response = await window.electronAPI.postWechatApi('/api/contact/list', {
      is_chatroom: true
    });
    
    if (response.code === 0) {
      groups.value = response.data || [];
      // 预选已保存的群组
      if (wechatStore.selectedGroups.length > 0) {
        selectedGroups.value = wechatStore.selectedGroups;
      }
      ElMessage.success('群组列表获取成功');
    } else {
      ElMessage.error(`获取群组列表失败: ${response.msg}`);
    }
  } catch (error) {
    ElMessage.error(`获取群组列表出错: ${error.message}`);
  } finally {
    isLoading.value = false;
  }
}

// 获取联系人列表
async function fetchContacts() {
  if (!wechatStore.isRunning) return;
  
  try {
    const response = await window.electronAPI.postWechatApi('/api/contact/list', {
      is_friend: true
    });
    
    if (response.code === 0) {
      contacts.value = response.data || [];
    } else {
      console.error(`获取联系人列表失败: ${response.msg}`);
    }
  } catch (error) {
    console.error(`获取联系人列表出错: ${error.message}`);
  }
}

// 查看群成员
async function viewGroupMembers(group) {
  selectedGroup.value = group;
  activeTab.value = 'users';
  
  isLoadingMembers.value = true;
  try {
    const response = await window.electronAPI.postWechatApi('/api/chatroom/members', {
      chatroom: group.wxid
    });
    
    if (response.code === 0) {
      users.value = response.data || [];
      // 预选已保存的用户
      if (wechatStore.selectedUsers.length > 0) {
        selectedUsers.value = wechatStore.selectedUsers;
      }
    } else {
      ElMessage.error(`获取群成员失败: ${response.msg}`);
    }
  } catch (error) {
    ElMessage.error(`获取群成员出错: ${error.message}`);
  } finally {
    isLoadingMembers.value = false;
  }
}

// 处理群组选择变化
function handleGroupSelectionChange(selection) {
  selectedGroups.value = selection;
  wechatStore.setSelectedGroups(selection);
}

// 处理用户选择变化
function handleUserSelectionChange(selection) {
  selectedUsers.value = selection;
  wechatStore.setSelectedUsers(selection);
}

// 显示添加规则对话框
function showAddRuleDialog() {
  isEditingRule.value = false;
  ruleForm.value = {
    name: '',
    sourceGroup: null,
    sourceUser: null,
    targetUser: null,
    enabled: true
  };
  ruleDialogVisible.value = true;
}

// 编辑规则
function editRule(rule, index) {
  isEditingRule.value = true;
  editingRuleIndex.value = index;
  ruleForm.value = { ...rule };
  ruleDialogVisible.value = true;
}

// 删除规则
function deleteRule(index) {
  ElMessageBox.confirm('确定要删除这条转发规则吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    wechatStore.removeForwardingRule(index);
    ElMessage.success('规则已删除');
  }).catch(() => {});
}

// 保存规则
function saveRule() {
  if (!ruleForm.value.name) {
    ElMessage.warning('请输入规则名称');
    return;
  }
  
  if (!ruleForm.value.sourceGroup) {
    ElMessage.warning('请选择来源群组');
    return;
  }
  
  if (!ruleForm.value.sourceUser) {
    ElMessage.warning('请选择来源用户');
    return;
  }
  
  if (!ruleForm.value.targetUser) {
    ElMessage.warning('请选择转发目标');
    return;
  }
  
  if (isEditingRule.value) {
    wechatStore.updateForwardingRule(editingRuleIndex.value, ruleForm.value);
    ElMessage.success('规则已更新');
  } else {
    wechatStore.addForwardingRule(ruleForm.value);
    ElMessage.success('规则已添加');
  }
  
  ruleDialogVisible.value = false;
}

// 组件挂载时
onMounted(() => {
  if (wechatStore.isRunning) {
    fetchGroups();
    fetchContacts();
  }
});
</script>

<style scoped>
.forwarding-container {
  max-width: 1000px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.tab-content {
  padding: 15px 0;
}

.search-input {
  margin-bottom: 15px;
  max-width: 300px;
}

.selected-group-info {
  margin-bottom: 15px;
}

.rules-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}
</style> 